namespace 屏幕截图
{
    public partial class Form1 : Form
    {
        private bool _isDrawing;
        private Point _startPoint,_endPoint;
        private Pen _pen;

        public Form1()
        {
            InitializeComponent();

            this.DoubleBuffered = true; // 开启双缓冲，减少绘图时的闪烁  
            _pen = new Pen(Color.Red, 2); // 创建画笔，设置颜色和粗细  
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 获取屏幕的主区域  
            Rectangle bounds = Screen.GetBounds(Point.Empty);

            // 创建一个与屏幕区域相同大小的Bitmap对象  
            using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
            {
                // 创建一个Graphics对象，用于绘制到Bitmap上  
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    // 将整个屏幕的内容绘制到Bitmap上  
                    g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
                }

                // 保存Bitmap到文件（如果需要）  
                string screenshotPath = "screenshot.png";
                bitmap.Save(screenshotPath, System.Drawing.Imaging.ImageFormat.Png);

                // Console.WriteLine("Screenshot saved to " + screenshotPath);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            _isDrawing = true;
            _startPoint = e.Location;
            textBox1.Text = e.Location.X.ToString();
            textBox2.Text = e.Location.Y.ToString();
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isDrawing)
            {
                this.Invalidate(); // 标记窗体需要重绘  
            }
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            _isDrawing = false;
            _endPoint = e.Location;
            this.Invalidate(); // 标记窗体需要重绘  
            textBox3.Text = e.Location.X.ToString();
            textBox4.Text = e.Location.Y.ToString();
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            if (_isDrawing)
            {
                Size size = new Size(_endPoint.X-_startPoint.X, _endPoint.Y-_startPoint.Y);
                Rectangle rect = new Rectangle(_startPoint,size);
                e.Graphics.DrawRectangle(_pen, rect); // 绘制矩形  

                textBox5.Text = size.Width.ToString();
                textBox6.Text = size.Height.ToString();
            }
        }
    }
}
